package com.alibaba.shopping_admin_service.service;

import com.alibaba.shopping_admin_service.mapper.AdminMapper;
import com.alibaba.shopping_admin_service.mapper.AdminRoleMapper;
import com.alibaba.shopping_common.pojo.Admin;
import com.alibaba.shopping_common.pojo.Permission;
import com.alibaba.shopping_common.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @ClassName AdminService
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/5 19:28
 */
@Transactional // 事务管理
@DubboService
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public void addAdmin(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void delAdmin(Long id) {
        // 删除bz_admin中的用户数据
        adminMapper.deleteById(id);
        // 删除bz_admin_role中的用户数据
        adminRoleMapper.delAdminRole(id);
    }

    @Override
    public void updateAdmin(Admin admin) {
        // 如果用户为填入密码，则使用之前的密码
        if (!StringUtils.hasText(admin.getPassword())){
            // 查询之前的密码
            Admin admin1 = adminMapper.selectById(admin.getAid());
            String password = admin1.getPassword();
            admin.setPassword(password);
        }
        adminMapper.updateById(admin);
    }

    @Override
    public Admin queryAdminById(Long aid) {
        return adminMapper.findAdminById(aid);
    }

    @Override
    public Page<Admin> queryAdminByPage(int num,int size) {
        // 分页查询
        return adminMapper.selectPage(new Page(num,size),null);
    }

    @Override
    public void updateAdminRole(Long aid, Long[] rids) {
        // 先删除管理员所有的权限信息
        adminRoleMapper.delAdminRole(aid);
        // 添加管理员的权限信息
        for (long rid:rids){
            adminRoleMapper.addRoleToAdmin(aid,rid);
        }
    }

    // 根据名称查询管理员(用于登录校验)
    @Override
    public Admin findByAdminName(String userName) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("userName",userName);
        Admin admin = adminMapper.selectOne(wrapper);
        System.out.println("根据名称查询管理员(用于登录校验),admin:"+admin);
        return admin;
    }

    // 根据名称查询管理员的全部权限(用于授权校验)
    @Override
    public List<Permission> findAllPermission(String userName) {
        List<Permission> allPermission = adminMapper.findAllPermission(userName);
        System.out.println("根据名称查询管理员的全部权限(用于授权校验)");
        System.out.println("allPermission:"+allPermission.toString());
        return allPermission;
    }
}




